﻿Imports EVOLTA.Promocion.Bl.Be
Imports EVOLTA.Promocion.Bl.Bc

Partial Class mantenedores_posibleCliente
    Inherits System.Web.UI.Page
    Implements System.Web.UI.ICallbackEventHandler

    Private posClientes As List(Of EposibleCliente) = Nothing
    Dim expression As String = Nothing
    Dim direction As SortDirection = SortDirection.Ascending

#Region "          Formulario                               "
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Response.CacheControl = "no-cache"
        Response.AddHeader("Pragma", "no-cache")
        Response.Expires = -1
        '***********************************************************'
        btnAgregar.Attributes.Add("onclick", "MuestraPanel(); return false;")

        ddlProvincia.Items.Add(New ListItem("-- SELECCIONE --", "0"))
        ddlDistrito.Items.Add(New ListItem("-- SELECCIONE --", "0"))

        ddlDepartamento.Attributes.Add("onchange", "if (this.options[this.selectedIndex].value == '00') {document.getElementById('ctl00$ContentPlaceHolder1$ddlDistrito').length=1;document.getElementById('ctl00$ContentPlaceHolder1$ddlProvincia').length=1;} else {document.getElementById('ctl00$ContentPlaceHolder1$ddlDistrito').length=1;CallTheServer('divddlProvincia@TN@' + this.options[this.selectedIndex].value + '00')};return false;")
        ddlProvincia.Attributes.Add("onchange", "if (this.options[this.selectedIndex].value == '00') {document.getElementById('ctl00$ContentPlaceHolder1$ddlDistrito').length=1;}else CallTheServer('divddlDistrito@TN@' + document.getElementById('ctl00$ContentPlaceHolder1$ddlDepartamento').value + this.options[this.selectedIndex].value + '00');return false;")
        'btnBuscar.Attributes.Add("onclick", "CallTheServer('divBuscar@' + document.getElementById('ctl00$ContentPlaceHolder1$txtBuscar').value);")

        Dim cbReference As String
        cbReference = Page.ClientScript.GetCallbackEventReference(Me, "arg", "ReceiveServerData", "null", True)

        Dim callbackScript As String = ""
        callbackScript &= "function CallTheServer(arg)" & _
                          "{" & cbReference & "; }"

        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "CallTheServer", callbackScript, True)
    End Sub
    Private Function Buscar(ByVal filtro As String) As IEnumerable(Of EposibleCliente)
        Dim Lposcli As System.Collections.Generic.IEnumerable(Of EposibleCliente) = Nothing
        posclientes = Session("lista")
        If Not posclientes Is Nothing Then
            If filtro.Length > 0 Then
                Dim x As Int32 = Asc(filtro.Substring(0, 1).Trim)
                If x >= 48 AndAlso x <= 57 Then
                    filtro = CType(filtro, Int32)
                    Lposcli = From p In posclientes _
                              Where p.idPosCliente = filtro _
                              Select p
                    Return Lposcli
                Else
                    Lposcli = From p In posclientes _
                              Where p.NombresCompletos Like "*" + filtro + "*" _
                              Select p
                End If
            Else
                Lposcli = From p In posclientes _
                              Where p.NombresCompletos Like "*" + filtro + "*" _
                              Select p
            End If
        End If
        Return Lposcli
    End Function
    Protected Sub lnkBtn_Command(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.CommandEventArgs) _
    Handles lnkBtnCodigo.Command, lnkBtnNombre.Command, lnkBtnTelefono.Command, lnkBtnEmail.Command, lnkBtnEstado.Command
        Dim posclientes As IEnumerable(Of EposibleCliente) = Buscar(txtBuscar.Value.ToUpper.Trim)
        Select Case e.CommandName
            Case "idPosCliente"
                Dim List = From d In posclientes _
                           Order By d.idPosCliente _
                           Select d
                gvwLista.DataSource = List
                gvwLista.DataBind()
            Case "NombresCompletos" : expression = e.CommandArgument
                Dim List = From d In posclientes _
                           Order By d.NombresCompletos _
                           Select d
                gvwLista.DataSource = List
                gvwLista.DataBind()
            Case "telefonoFijo" : expression = e.CommandArgument
                Dim List = From d In posclientes _
                           Order By d.telefonoFijo _
                           Select d
                gvwLista.DataSource = List
                gvwLista.DataBind()
            Case "email" : expression = e.CommandArgument
                Dim List = From d In posclientes _
                           Order By d.email _
                           Select d
                gvwLista.DataSource = List
                gvwLista.DataBind()
            Case "descEstado" : expression = e.CommandArgument
                Dim List = From d In posclientes _
                           Order By d.descEstado _
                           Select d
                gvwLista.DataSource = List
                gvwLista.DataBind()
        End Select
    End Sub
    Protected Sub gvwLista_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvwLista.PageIndexChanging
        posclientes = Session("lista")
        If Not posclientes Is Nothing Then
            Me.gvwLista.DataSource = posclientes
            Me.gvwLista.PageIndex = e.NewPageIndex
            Me.gvwLista.DataBind()
            upPosCliente.Update()
        End If
    End Sub
    Protected Sub gvwLista_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
    Handles gvwLista.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            e.Row.Attributes.Add("OnMouseOver", "Resaltar_On(this);")
            e.Row.Attributes.Add("OnMouseOut", "Resaltar_Off(this);")
            'e.Row.Attributes.Add("OnClick", "CallTheServer('showDet@" + e.Row.RowIndex.ToString + "');")
            e.Row.Style.Add("cursor", "hand")
        End If
    End Sub
    Private Function obtenerEdit(ByVal pLposClientes As System.Collections.Generic.IEnumerable(Of EposibleCliente)) As String
        Dim datos As New StringBuilder
        datos.Append(pLposClientes.ElementAt(0).idPosCliente.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).EtpoDcmto.idTpoDcmto.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).nroDocumento + "|")
        datos.Append(pLposClientes.ElementAt(0).nombre.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).apePaterno.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).apeMaterno.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).sexo.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).EestadoCivil.idEstCivil.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).edad.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).telefonoFijo.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).telefonoCelular.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).telefonoLaboral.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).Eubigeo.idUbigeo.Substring(0, 2) + "|")
        datos.Append(pLposClientes.ElementAt(0).Eubigeo.idUbigeo.Substring(2, 2) + "|")
        datos.Append(pLposClientes.ElementAt(0).Eubigeo.idUbigeo.Substring(4, 2) + "|")
        datos.Append(pLposClientes.ElementAt(0).Eocupacion.idOcupacion.ToString + "|")
        datos.Append(pLposClientes.ElementAt(0).email.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).direccion.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).centroLaboral.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).comentarios.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).estado.Trim + "|")
        datos.Append(pLposClientes.ElementAt(0).OtroDocumento.Trim)
        Return datos.ToString()
    End Function
    Protected Sub btnExcel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExcel.Click
        posclientes = Session("lista")
        If Not posclientes Is Nothing Then
            Dim fileName As String = "Consulta{0}.xls"
            fileName = String.Format(fileName, DateTime.Now.ToShortDateString())
            Dim Response As HttpResponse = HttpContext.Current.Response
            Response.ContentType = "application/vnd.ms-excel"
            Response.Charset = "UTF-8"
            Response.ContentEncoding = System.Text.Encoding.Default
            Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName)

            Response.Write("id")
            Response.Write(vbTab)
            Response.Write("Nombres")
            Response.Write(vbTab)
            Response.Write("Apellido Paterno")
            Response.Write(vbTab)
            Response.Write("Apellido Materno")
            Response.Write(vbTab)
            Response.Write("Tipo Documento")
            Response.Write(vbTab)
            Response.Write("Nro de Documento")
            Response.Write(vbTab)
            Response.Write("Sexo")
            Response.Write(vbTab)
            Response.Write("Edad")
            Response.Write(vbTab)
            Response.Write("Estado Civil")
            Response.Write(vbTab)
            Response.Write("Nacionalidad")
            Response.Write(vbTab)
            Response.Write("Email")
            Response.Write(vbTab)
            Response.Write("Dirección")
            Response.Write(vbTab)
            Response.Write("Teléfono Fijo")
            Response.Write(vbTab)
            Response.Write("Teléfono Celular")
            Response.Write(vbTab)
            Response.Write("Ocupación")
            Response.Write(vbTab)
            Response.Write("Nro Partida")
            Response.Write(vbTab)
            Response.Write("Centro Laboral")
            Response.Write(vbTab)
            Response.Write("Teléfono Laboral")
            Response.Write(vbTab)
            Response.Write("Comentario")
            Response.Write(vbTab)
            Response.Write(vbCrLf)

            Dim value As String
            For Each poscliente In posclientes
                value = poscliente.idPosCliente
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.nombre
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.apePaterno
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.apeMaterno
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.EtpoDcmto.descTpoDcmto
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.nroDocumento
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.descSexo
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.edad
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.EestadoCivil.desEstCivil
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.nacionalidad
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.email
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.direccion
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.telefonoFijo
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.telefonoCelular
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.Eocupacion.descOcupacion
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.nroPartida
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.centroLaboral
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.telefonoLaboral
                Response.Write(value)
                Response.Write(vbTab)

                value = poscliente.comentarios
                Response.Write(value)
                Response.Write(vbCrLf)
            Next
            Response.End()
        Else
            Dim jsMensaje As String = Nothing
            jsMensaje = "<script>javascript:alert(' La consulta no pudo ser procesada.  Por favor inténtelo de nuevo.');</script>)"
            Controls.Add(New LiteralControl(jsMensaje))
        End If
    End Sub
#End Region

#Region "          CallBack                                 "
    Private _callbackArgument As String
    Public Function GetCallbackResult() As String Implements System.Web.UI.ICallbackEventHandler.GetCallbackResult
        Return _callbackArgument
    End Function
    Public Sub RaiseCallbackEvent(ByVal eventArgument As String) Implements System.Web.UI.ICallbackEventHandler.RaiseCallbackEvent
        Try
            If eventArgument <> String.Empty Then
                Dim varParams() As String = eventArgument.Split("@")
                Dim sr As New System.IO.StringWriter()
                Dim htm As New HtmlTextWriter(sr)
                _callbackArgument = ""
                Select Case varParams(0)
                    Case "divddlDepartamento"
                        Me.ddlDepartamento.DataSource = Rubigeo.SeleccionarTodoXDepartamento(Me.Master.descEmpresa, True)
                        Me.ddlDepartamento.DataTextField = "descripcion"
                        Me.ddlDepartamento.DataValueField = "idUbigeo"
                        Me.ddlDepartamento.DataBind()
                        Me.ddlDepartamento.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlProvincia"
                        Me.ddlProvincia.DataSource = Rubigeo.SeleccionarTodoXProvincia(Me.Master.descEmpresa, True, varParams(2).ToString.Substring(0, 2))
                        Me.ddlProvincia.DataTextField = "descripcion"
                        Me.ddlProvincia.DataValueField = "idUbigeo"
                        Me.ddlProvincia.DataBind()
                        Me.ddlProvincia.Value = varParams(2).ToString.Substring(2, 2)
                        If varParams(1).Substring(0, 1).Equals("F") AndAlso Not varParams(1).Substring(1, 1).Equals("N") Then
                            Me.ddlProvincia.Disabled = True
                        Else
                            Me.ddlProvincia.Disabled = False
                        End If
                        Me.ddlProvincia.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlDistrito"
                        Me.ddlDistrito.DataSource = Rubigeo.SeleccionarTodoXDistrito(Me.Master.descEmpresa, True, varParams(2).ToString.Substring(0, 2), varParams(2).ToString.Substring(2, 2))
                        Me.ddlDistrito.DataTextField = "descripcion"
                        Me.ddlDistrito.DataValueField = "idUbigeo"
                        Me.ddlDistrito.DataBind()
                        Me.ddlDistrito.Value = varParams(2).ToString.Substring(4, 2)
                        If varParams(1).Substring(0, 1).Equals("F") AndAlso Not varParams(1).Substring(1, 1).Equals("N") Then
                            Me.ddlDistrito.Disabled = True
                        Else
                            Me.ddlDistrito.Disabled = False
                        End If
                        Me.ddlDistrito.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divgvwLista"
                        posclientes = RposibleCliente.SeleccionarTodoMantenedor(Me.Master.descEmpresa, False)
                        Session("lista") = posclientes
                        If Not posclientes Is Nothing Then
                            Me.gvwLista.DataSource = posclientes
                            Me.gvwLista.DataBind()
                            Me.gvwLista.RenderControl(htm)
                        End If
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlTpoDcmto"
                        Me.selTpoDocmto.DataSource = RtpoDcmto.SeleccionarTodo(Me.Master.descEmpresa, True)
                        Me.selTpoDocmto.DataTextField = "descTpoDcmto"
                        Me.selTpoDocmto.DataValueField = "idTpoDcmto"
                        Me.selTpoDocmto.DataBind()
                        Me.selTpoDocmto.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlSexo"
                        Dim Esexo As New Ecommons
                        Me.selSexo.DataSource = Esexo.sexo
                        Me.selSexo.DataTextField = "descripcion"
                        Me.selSexo.DataValueField = "codigo"
                        Me.selSexo.DataBind()
                        Me.selSexo.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlOcupacion"
                        Me.selOcupacion.DataSource = Rocupacion.SeleccionarXEstado(Me.Master.descEmpresa, True)
                        Me.selOcupacion.DataTextField = "descOcupacion"
                        Me.selOcupacion.DataValueField = "idOcupacion"
                        Me.selOcupacion.DataBind()
                        Me.selOcupacion.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlEstadoCivil"
                        Me.selEstadoCivil.DataSource = RestadoCivil.SeleccionarTodo(Me.Master.descEmpresa, True)
                        Me.selEstadoCivil.DataTextField = "desEstCivil"
                        Me.selEstadoCivil.DataValueField = "idEstCivil"
                        Me.selEstadoCivil.DataBind()
                        Me.selEstadoCivil.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divddlEstado"
                        Dim Eestado As New Ecommons
                        Me.selEstado.DataSource = Eestado.estado
                        Me.selEstado.DataTextField = "descripcion"
                        Me.selEstado.DataValueField = "codigo"
                        Me.selEstado.DataBind()
                        Me.selEstado.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = varParams(0).ToString + "|" + sr.ToString()
                    Case "divBuscar"
                        'Me.gvwLista.DataSource = Buscar(varParams(1).ToUpper.Trim)
                        Dim pPos As New EposibleCliente With {.filtro = varParams(1).ToUpper.Trim}
                        posClientes = RposibleCliente.BuscarMantenedor(Me.Master.descEmpresa, False, pPos)
                        Session("lista") = posClientes
                        Me.gvwLista.DataSource = posClientes
                        Me.gvwLista.DataBind()
                        Me.gvwLista.RenderControl(htm)
                        htm.Flush()
                        _callbackArgument = "divgvwLista|" + sr.ToString()
                    Case "showDet"
                        Dim id As Int32 = CType(varParams(1), Int32)
                        posClientes = Session("lista")
                        _callbackArgument = "detalle|showDet|Posible Cliente [Modificar]|" + obtenerEdit(From pc In posClientes Where pc.idPosCliente = id Select pc)
                    Case "delete"
                        Dim pPosibleCliente As New EposibleCliente
                        With pPosibleCliente
                            .idPosCliente = CType(varParams(1), Int32)
                            .idUsuario = Me.Master.idUsuario
                        End With
                        RposibleCliente.EliminarMantenedor(Me.Master.descEmpresa, pPosibleCliente)
                    Case "savePosibleCliente"
                        Dim pPosibleCliente As EposibleCliente = Nothing
                        pPosibleCliente = New EposibleCliente
                        With pPosibleCliente
                            .idPosCliente = CType(varParams(2), Int32)
                            .EtpoDcmto = New EtpoDcmto
                            .EtpoDcmto.idTpoDcmto = CType(varParams(3), Int32)
                            .nroDocumento = varParams(4)
                            .nombre = varParams(5).ToUpper.Trim
                            .apePaterno = varParams(6).ToUpper.Trim
                            .apeMaterno = varParams(7).ToUpper.Trim
                            .sexo = CType(varParams(8), Int32)
                            .EestadoCivil = New EestadoCivil
                            .EestadoCivil.idEstCivil = CType(varParams(9), Int32)
                            If varParams(10).Equals("") Then
                                .edad = 0
                            Else
                                .edad = CType(varParams(10), Int32)
                            End If
                            .telefonoFijo = varParams(11).Trim
                            .telefonoCelular = varParams(12).Trim
                            .telefonoLaboral = varParams(13).Trim
                            .Eubigeo = New Eubigeo
                            .Eubigeo.idUbigeo = varParams(14) + _
                                               varParams(15).PadLeft(2, "0") + _
                                               varParams(16).PadLeft(2, "0")
                            .Eocupacion = New Eocupacion
                            .Eocupacion.idOcupacion = CType(varParams(17), Int32)
                            If varParams(18).ToUpper.Trim.Equals("") Then
                                .email = ""
                                .direccion = varParams(19).Trim.ToUpper
                                .centroLaboral = varParams(20).Trim.ToUpper
                                .comentarios = varParams(21).Trim.ToUpper
                                .estado = varParams(22)
                            Else
                                .email = varParams(18).ToUpper.Trim + "@" + varParams(19).ToUpper.Trim
                                .direccion = varParams(20).Trim.ToUpper
                                .centroLaboral = varParams(21).Trim.ToUpper
                                .comentarios = varParams(22).Trim.ToUpper
                                .estado = varParams(23)
                            End If
                            .idUsuario = Me.Master.idUsuario
                            .OtroDocumento = varParams(24)
                        End With

                        Dim resultado As Boolean = 0
                        If varParams(1) = "Registrar" Then
                            resultado = RposibleCliente.AñadirMantenedor(Me.Master.descEmpresa, pPosibleCliente)
                        ElseIf varParams(1) = "Modificar" Then
                            resultado = RposibleCliente.EditarMantenedor(Me.Master.descEmpresa, pPosibleCliente)
                        End If

                        posclientes = RposibleCliente.SeleccionarTodoMantenedor(Me.Master.descEmpresa, False)
                        Session("lista") = posclientes
                        If Not posclientes Is Nothing Then
                            Me.gvwLista.DataSource = posclientes
                            Me.gvwLista.DataBind()
                        End If
                        Me.gvwLista.RenderControl(htm)

                        _callbackArgument = "divgvwLista|savePosibleCliente|" + varParams(1) + "|" + resultado.ToString + "|" + sr.ToString()
                End Select
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
#End Region

End Class

